<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :mask-closable="false"
    :visible="visible"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
    <div class="g-drawer-list-container">
      <div class="g-drawer-progress-container">
        <TitleSecondary title="审批流程图" />
        <ProgressStaus />
      </div>
      <ProgressGraph :data="detail.nodeFlowChartList" />
      <TitleSecondary title="基本信息" />
      <FormBasicInfo :is-edit="false" :form="form" :page-type="pageType" />
      <TitleSecondary title="销售责任人" />
      <TableSaleListSecondary
        :data-source="detail.mforecastSalesList"
        :page-type="pageType"
        style="margin-bottom: 20px"
      />
      <TitleSecondary title="预测明细" />
      <p-tabs
        class="g-drawer-poros-tabs"
        :default-active-key="'4'"
        type="card"
        @change="handleTabChange"
      >
        <p-tab-pane key="1" :tab="'FCST'">
          <TablePlanDetail
            ref="table-detail"
            :data-source="planDetailList"
            :is-edit="false"
            :plan-id="planId"
            :mforecast-sales-id="detail.mforecastSalesId"
            :plan-sales="detail.mforecastSalesList"
            :detail-copy="detailStartCopy"
            :plan-type="planType"
            :hide-keys="['selection']"
            local-key="m3-group-audit-secondary-fcst"
            :buttons="[
              {
                key: 'export',
                label: '导出',
              },
              {
                key: 'show',
                label: '显示字段',
              },
              {
                key: 'screenfull',
                label: '全屏显示',
              },
            ]"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            @checked="handleTableCheckedChange"
          />
        </p-tab-pane>
        <p-tab-pane key="2">
          <span slot="tab">执行版预测</span>
          <TablePlanDetailPre
            ref="table-detail"
            :data-source="endPlanDetailList"
            :plan-sales="detail.mforecastSalesList"
            :plan-id="planId"
            :is-edit="false"
            :is-pre-edit="false"
            :plan-type="planType"
            :hide-keys="['selection']"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            :plan-sales-id="detail.planSalesId"
            local-key="m3-group-audit-secondary-pre"
            :buttons="[
              {
                key: 'export',
                label: '导出',
              },
              {
                key: 'show',
                label: '显示字段',
              },
              {
                key: 'screenfull',
                label: '全屏显示',
              },
            ]"
          />
        </p-tab-pane>
        <p-tab-pane key="3">
          <span slot="tab">供应计划</span>
          <TablePlanDetailSupply
            ref="table-detail"
            :data-source="thirdDetailList"
            :plan-sales="detail.mforecastSalesList"
            :plan-id="planId"
            :is-edit="false"
            :is-pre-edit="false"
            :plan-type="planType"
            :hide-keys="['selection']"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            :plan-sales-id="detail.planSalesId"
            local-key="m3-group-audit-secondary-supply"
            :buttons="[
              {
                key: 'export',
                label: '导出',
              },
              {
                key: 'show',
                label: '显示字段',
              },
              {
                key: 'screenfull',
                label: '全屏显示',
              },
            ]"
          />
        </p-tab-pane>
        <p-tab-pane key="4">
          <span slot="tab">销售预测</span>
          <TablePlanDetailSale
            ref="table-detail"
            :data-source="fourthDetailList"
            :plan-sales="detail.mforecastSalesList"
            :plan-id="planId"
            :is-edit="false"
            :is-pre-edit="false"
            :plan-type="planType"
            :hide-keys="['selection']"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            :plan-sales-id="detail.planSalesId"
            local-key="m3-group-audit-secondary-sale"
            :buttons="[
              {
                key: 'show',
                label: '显示字段',
              },
              {
                key: 'screenfull',
                label: '全屏显示',
              },
            ]"
          />
        </p-tab-pane>
        <p-tab-pane key="5">
          <span slot="tab">总览</span>
          <TablePlanDetailTotal
            :data-source="totalDetailList"
            :plan-sales="detail.mforecastSalesList"
            :plan-id="planId"
            :plan-type="planType"
            :hide-keys="['selection']"
            :time-range="[form.startTime, form.endTime]"
            :plan-sales-id="detail.planSalesId"
            local-key="m3-group-audit-secondary-total"
            @checked="handleTableCheckedChange"
          />
        </p-tab-pane>
      </p-tabs>

      <TitleSecondary v-if="hasEdit" title="审批信息" />
      <ApprovalInformation v-if="hasEdit" ref="approval" :has-copy="false" />
      <ProgressLog :list="logList" />
      <BottomLine />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
    <DialogTransfer
      :visible.sync="visibleTransfer"
      :plan-id="planId"
      @change="onClose"
    />
  </p-drawer>
</template>

<script>
import FormBasicInfo from './FormBasicInfo.vue';
import TableSaleListSecondary from './TableSaleListSecondary.vue';
import ProgressGraph from '@/components/task/ProgressGraph.vue';
import ProgressLog from '@/components/task/ProgressLog.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';
import TablePlanDetail from './TablePlanDetail.vue';
import TablePlanDetailPre from './TablePlanDetailPre.vue';
import TablePlanDetailSale from './TablePlanDetailSale.vue';
import TablePlanDetailSupply from './TablePlanDetailSupply.vue';
import TablePlanDetailTotal from './TablePlanDetailTotal.vue';

import DialogTransfer from '@/components/dialog/DialogTransferForecast.vue';
import ApprovalInformation from '@/components/task/ApprovalInformation.vue';

import { postSalesApproveSecondary } from '@/api/forecast';

import DrawerMixin from './mixin';
import { isEmpty } from '@/utils/is';

const requireKey = [
  'customerCode',
  'modelName',
  'modelNumber',
  'application',
  'appearance',
  'modelCutRate',
];

const buttons = [
  {
    key: 'insert',
    label: '导入',
  },
  {
    key: 'delete',
    label: '删除',
  },
  {
    key: 'download',
    label: '下载模板',
  },
];
export default {
  components: {
    FormBasicInfo,
    TablePlanDetail,
    TableSaleListSecondary,
    ProgressGraph,
    ProgressLog,
    ProgressStaus,
    ApprovalInformation,
    DialogTransfer,
    TablePlanDetailPre,
    TablePlanDetailSale,
    TablePlanDetailSupply,
    TablePlanDetailTotal,
  },

  mixins: [DrawerMixin],

  props: {},
  data() {
    this.buttons = buttons;
    return {
      planDetailList: [],
      visibleTransfer: false,
    };
  },
  computed: {
    form() {
      return this.detail.plan || {};
    },
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  methods: {
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    closeCallback() {
      this.onClose();
    },
    // async submitData(operating, handleResult) {
    //   const endPlanDetailList = this.thirdDetailList.map((item) => {
    //     const fcst = Object.keys(item).reduce((pre, cur) => {
    //       if (cur.startsWith('fcstmonth')) {
    //         const month = cur.split('_')[1];
    //         month !== 'total' && (pre[month] = item[cur]);
    //       }
    //       return pre;
    //     }, {});

    //     return {
    //       appearance: item.appearance,
    //       application: item.application,
    //       customerCode: item.customerCode?.key,
    //       customerName: item.customerCode?.label,
    //       innerItem: item.innerItem,
    //       item: item.item,
    //       manufactureArea: item.manufactureArea,
    //       modelCutRate: item.modelCutRate,
    //       modelCode: item.modelName?.key,
    //       modelName: item.modelName?.label,
    //       modelNumber: item.modelNumber?.key,
    //       modelInfoName: item.modelNumber?.label,
    //       remark: item.remark,
    //       preAllocated: JSON.stringify(fcst),
    //       salesGroupName: item.salesGroupName,
    //       planSalesId: item.planSalesId,
    //     };
    //   });
    //   if (operating === 0) {
    //     const isValid = this.checkData(endPlanDetailList);
    //     if (!isValid) return new Promise(() => {});

    //     return await postGroupEntryForecast({
    //       id: this.planId,
    //       operating,
    //       salesForecastList: endPlanDetailList,
    //       handleResult,
    //     });
    //   } else {
    //     return await postGroupEntryForecast({
    //       id: this.planId,
    //       operating,
    //       salesForecastList: endPlanDetailList,
    //     });
    //   }
    // },
    // async submitCallback() {
    //   const data = this.$refs.approval?.form || {};
    //   if (!data.approveOpinion) {
    //     this.$message.error('请先填写意见！');
    //     return;
    //   }
    //   await this.submitData(0, data.approveOpinion);
    //   this.$message.success('提交成功！');
    //   this.closeCallback();
    // },
    async submitCallback() {
      const data = this.$refs.approval?.form || {};
      if (typeof data.approveStatus !== 'boolean') {
        this.$message.error('请先进行审批！');
        return;
      }
      if (data.approveStatus === false && !data.approveOpinion) {
        this.$message.error('请填写审批意见！');
        return;
      }

      const formatData = {
        handleResult: data.approveStatus ? 0 : 1,
        handleRemark: data.approveOpinion,
        makeCopy: data.makeCopy,
      };

      const planSalesId = this.planDetailList[0]?.mforecastSalesId;
      await postSalesApproveSecondary({
        ...formatData,
        mforecastId: this.planId,
        mforecastSalesId: planSalesId,
      });
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    async saveCallback() {
      await this.submitData(1);
      this.$message.success('保存成功！');
      this.closeCallback();
    },

    checkData(list) {
      console.log('list: ', list);
      if (!list.length) {
        this.$message.error('请先填写表格内容！');
        return false;
      }
      const index = list.findIndex((item) => {
        const fcst = JSON.parse(item.preAllocated || '{}');
        const isFcst = Object.keys(fcst).some((key) => isEmpty(fcst[key]));
        return isFcst || requireKey.some((key) => isEmpty(item[key]));
      });
      if (index > -1) {
        this.$message.error('预分配数据未填写完整，请补充！');
        return false;
      }
      return true;
    },

    async transferCallback() {
      this.visibleTransfer = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>
